package com.apes.fn.scm.retailReturn;

import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.BaseModel;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.util.ApesConst;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.account.tax.service.TaxService;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.service.UomService;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Map;

/**
 * 功能：销售订单
 *
 * @author xul
 * @create 2018-01-25 19:36
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = RetailReturnItem.CONST_TABLE_NAME)
public class RetailReturnItem extends BaseModel {
    public static final String CONST_TABLE_NAME = "retail_return_item";

    @Id
    @Column(name = "id")
    @ApesGenerator(code = CONST_TABLE_NAME, name = "销售退回明细")
    private String id;

    @ManyToOne(optional = false)
    @JoinColumn(name="sale_id", referencedColumnName="id", nullable = false)
    @Comment("退货单编码")
    private RetailReturn order;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "retail_order_item_id", referencedColumnName = "id")
    @Comment("原订单行号")
    private RetailOrderItem retailOrderItem;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "location_id", referencedColumnName = "id")
    private Location location;  //库存位置

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "supplier_id", referencedColumnName = "id")
    @Comment("供应商")
    private PartyRole supplier;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", referencedColumnName = "id", nullable = false)
    @Comment("商品")
    private Product product;

    @Column(name = "remark", length = 120)
    @Comment("备注")
    private String remark;

    @Column(name = "price_subtotal", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("小计（未含税金额）")
    private double priceSubtotal = 0;

    @Column(name = "price_tax", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("税金")
    private double priceTax = 0;

    @Column(name = "price_total", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计")
    private double priceTotal = 0;

    @Column(name = "price_unit", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("单价")
    private double priceUnit = 0;

    @Column(name = "product_uom_qty", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("数量")
    private double productUomQty = 0;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_uom_id", referencedColumnName = "id", nullable = false)
    @Comment("计量单位")
    private ProductUom uom;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "tax_id", referencedColumnName = "id", nullable = false)
    @Comment("税率")
    private Tax tax;

    @Column(name = "qty_invoiced", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("开票数量")
    private double qtyInvoiced = 0;

    @Column(name = "qty_received", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("收货数量")
    private double qtyDeliver = 0;

    @Column(name = "qty_delivering", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("提单冲红数量")
    private double qtyDelivering = 0;

    @Column(name = "qty_delivered", nullable = false, columnDefinition = ApesConst.FIELD_QTY_16_4_0)
    @Comment("退货冲红数量")
    private double qtyDelivered = 0;

    @Column(name = "pack_id", length = 128)
    @Comment("套包编码")
    private String packId;

    @Transient
    private double qtyDeliveringLimit = 0;

    @Transient
    private double qtyDeliveredLimit = 0;

    public double getQtyDeliveringLimit() {
        if (retailOrderItem == null) return 0;
        return retailOrderItem.getQtyDeliveringLimit() + qtyDelivering;
    }

    public double getQtyDeliveredLimit() {
        if (retailOrderItem == null) return 0;
        return retailOrderItem.getQtyDeliveringLimit() + qtyDelivered;
    }


    @Column(name = "discount_amount", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("折扣金额")
    private double discountAmount = 0;

    @Transient
    private PartyRole owner; //物权公司

    public PartyRole getOwner() {
        if (location != null) return location.getCompany();
        return company;
    }

    public void setQtyDelivering(double qtyDelivering) {
        if (qtyDelivering < 0) {
            throw new RuntimeException("提单冲红数量不能小于0");
        }
        this.qtyDelivering = qtyDelivering;
    }

    public void setQtyDelivered(double qtyDelivered) {
        if (qtyDelivered < 0) {
            throw new RuntimeException("退货冲红数量不能小于0");
        }
        this.qtyDelivered = qtyDelivered;
    }

    public double getProductUomQty() {
        if (productUomQty < 0) {
            throw new RuntimeException("退货数量不能小于0");
        }
        return productUomQty;
    }

    /**
     * 重新计算数量
     */
    public void computeAmt() {
        Map result = this.computeTax().computeAll(this.getCompany(), priceUnit, productUomQty);
        priceTax = ((Double) result.get("taxAmt")).doubleValue();
        priceSubtotal = ((Double) result.get("totalExcluded")).doubleValue();
        priceTotal = ((Double) result.get("totalIncluded")).doubleValue();
        double recalculateTotal = priceTotal - (priceUnit * productUomQty);
        if (Math.abs(recalculateTotal) > 1) {
            throw new RuntimeException(String.format("商品[%s]计算金额有误，请重新确认单据！", product.getName()));
        }
    }

    private Tax computeTax() {
        TaxService taxService = SpringManager.getBean(TaxService.class);
        tax = taxService.getSaleTax(order.getCompany(), product);
        return tax;
    }

    /***
     * 功能：合计退货数量
     * @param
     */
    public void sumProductUomQty() {
        this.productUomQty = this.qtyDelivering + this.qtyDelivered;
    }

    /**
      * 功能：计算无税库存单价
      */
    public double computeExcludedPriceUnit() {
        double price = this.priceUnit;
        if (this.getTax() != null) {
            price = (double) this.getTax().computeAll(this.getOrder().getCompany(), price, 1.0).get("totalExcluded");
        }
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /**
     * 功能：计算含税库存单价
     */
    public double computePriceUnit() {
        double price = this.priceUnit;
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            price = this.getUom().computePrice(price, baseUom);
        }
        return price;
    }

    /**
     * 功能：计算基本单位库存量
     */
    public double computeQtyUnit(double uomQty) {
        ProductUom baseUom = getProductUom();
        if (this.getUom().getId() != baseUom.getId()) {
            return this.getUom().computeQty(uomQty, baseUom, true);
        }
        return uomQty;
    }

    private ProductUom getProductUom() {
        UomService uomService = SpringManager.getBean(UomService.class);
        return uomService.getUom(this.getCompany(), this.getProduct());
    }

    /**
     * 交货
     */
    public void delivery(double qtyDone) {
        this.qtyDeliver += qtyDone;
        if (qtyDeliver > productUomQty) {
            throw new RuntimeException("发货数量不允许大于订单数量！");
        }
    }

}
